package com.drools.rule.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.drools.rule.build.BaseRuleBuild;
import com.drools.rule.build.RuleBuildFactory;
import com.drools.rule.entity.DrlContext;
import com.drools.rule.execute.RuleExecute;
import com.drools.rule.req.ActionReq;
import com.drools.rule.req.LoginActionReq;
import com.drools.rule.req.RuleReq;
import com.drools.rule.service.RuleService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;


@Service
public class RuleServiceImpl implements RuleService {

    @Resource
    private RuleExecute ruleExecute;

    @Override
    public Boolean create(RuleReq ruleReq) {
        BaseRuleBuild baseRuleBuild = RuleBuildFactory.getBuildService(ruleReq.getActionType());
        DrlContext drlContext = baseRuleBuild.getDrlContext(ruleReq);

        //在实际项目中 drlContext.toString() 个内容需要落库存储并做一些防重验证等逻辑
        RuleBuildFactory.addRules(ruleReq.getSubActionType(), drlContext.toString());

        System.out.println(drlContext.toString());
        return true;
    }

    @Override
    public Boolean execute(LoginActionReq loginActionReq) {
        //这里需要去数据库查询出用户的登录次数,这里测试方便就用传过来的值
        loginActionReq.setLoginNum(loginActionReq.getLoginNum());

        List<String> rulesContext = RuleBuildFactory.getRules(loginActionReq.getLoginActionType());
        ActionReq actionReq = ruleExecute.execute(rulesContext, loginActionReq);
        System.out.println(JSONObject.toJSONString(actionReq));
        return true;
    }
}
